import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Order.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:flutter_chip/widget/widget_paysuccess.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart' as fluwx;

class MemberPage extends StatefulWidget {
  User user;

  MemberPage(this.user);

  @override
  _MemberPageState createState() => _MemberPageState();
}

class _MemberPageState extends State<MemberPage> {
  List listVip1 = [
    {
      "text": "修改昵称",
      "icon": Comm.IMG_V_EDIT,
    },
    {
      "text": "尊贵身份",
      "icon": Comm.IMG_V_MARK,
    },
    {
      "text": "赚钱",
      "icon": Comm.IMG_V_MM,
    },
  ];

  List listVip2 = [
    {
      "text": "个性背景",
      "icon": Comm.IMG_V_BG,
    },
  ];

  bool loading = false;
  String orderId;

  @override
  void initState() {
    super.initState();
    fluwx.registerWxApi(
        appId: Comm.WX_APPID,
        universalLink: "https://your.univeral.link.com/placeholder/");
    fluwx.weChatResponseEventHandler.listen((res) {
      if (res is fluwx.WeChatPaymentResponse) {
        if (res.isSuccessful) {
          String url = "${Api.URL_ORDER_INFO}?orderId=$orderId";
          Http.get(url, successCallBack: (data) {
            Order order = Order.fromJson(json.decode(data));
            Navigator.of(context).push(RouteSlide(
              PaySuccess(
                order.updateAt,
                order.orderId,
                order.payCode,
                "${order.price}",
              ),
            ));
          });
        } else if (res.errCode == -2) {
          Toast.show("支付已取消");
        } else {
          Toast.show("支付失败");
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Theme.of(context).canvasColor,
        titleSpacing: 0.0,
        title: Text("会员中心", style: TextStyle(fontSize: 18)),
      ),
      body: ProgressDialog(
        loading: loading,
        msg: "创建订单中...",
        child: Column(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    _vip1Widget(),
                    _priceWidget(),
                    Container(
                      height: 10,
                      color: Color(0xffEEEEEE),
                    ),
                    _payWidget(),
                  ],
                ),
              ),
            ),
            Divider(thickness: 1, color: Color(0xffEEEEEE), height: 1),
            _bottomWidget(),
          ],
        ),
      ),
    );
  }

  Widget _vip1Widget() {
    Widget _iconWidget = Container(
      width: 36,
      height: 36,
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
      ),
      child: Image.asset(
        Comm.IMG_IC_VIP,
        width: 24,
        height: 24,
        color: Color(0xffF0B410),
      ),
    );

    Widget _typeWidget = Container(
      margin: EdgeInsets.only(left: 46),
      height: 36,
      alignment: Alignment.centerLeft,
      child: Text(
        widget.user.vip == 1 ? "VIP会员" : "普通会员",
        style: TextStyle(
          color: Colors.white,
          fontSize: 18,
          fontWeight: FontWeight.w400,
        ),
      ),
    );

    Widget _hint1Widget = Container(
      margin: EdgeInsets.only(top: 56),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: listVip1
            .map((item) => Builder(
                  builder: (context) {
                    return _vipHintWidget(item["text"], item["icon"]);
                  },
                ))
            .toList(),
      ),
    );
    Widget _hint2Widget = Container(
      margin: EdgeInsets.only(top: 90),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: listVip2
            .map((item) => Builder(
                  builder: (context) {
                    return _vipHintWidget(item["text"], item["icon"]);
                  },
                ))
            .toList(),
      ),
    );
    String term = "";
    if (null != widget.user.vipTerm) {
      term = widget.user.vipTerm.split(" ")[0];
    }

    Widget _termWidget = Offstage(
      offstage: widget.user.vip == 0,
      child: Container(
        margin: EdgeInsets.only(top: 10),
        child: Text(
          "$term到期",
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
    return Container(
      width: Comm.screenWidth,
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      padding: EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.bottomLeft,
          end: Alignment.topRight,
          colors: [
            Color(0xffF0B410),
            Color(0xffF2A912),
          ],
        ),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Stack(
        children: <Widget>[
          Align(alignment: Alignment.topLeft, child: _iconWidget),
          Align(alignment: Alignment.topLeft, child: _typeWidget),
          Align(alignment: Alignment.center, child: _hint1Widget),
          Align(alignment: Alignment.center, child: _hint2Widget),
          Align(alignment: Alignment.centerRight, child: _termWidget),
        ],
      ),
    );
  }

  Widget _vipHintWidget(String text, String icons) {
    return Row(
      children: <Widget>[
        Offstage(
          offstage: null == icons,
          child: Image.asset(
            icons,
            color: Colors.white,
            width: 20,
            height: 20,
          ),
        ),
        SizedBox(width: 6),
        Text(
          text,
          style: TextStyle(color: Colors.white),
        ),
      ],
    );
  }

  List _price = [
    {
      "id": 0,
      "num": 1,
      "title": "一个月",
      "price": "9.9",
      "oldPrice": "15",
      "disc": "0",
    },
    {
      "id": 1,
      "num": 3,
      "title": "三个月",
      "price": "39.9",
      "oldPrice": "45",
      "disc": "5.1",
    },
    {
      "id": 2,
      "num": 6,
      "title": "半年",
      "price": "59.9",
      "oldPrice": "80",
      "disc": "20.1",
    },
  ];
  int current = 0;
  Color borderColor = Color(0xffFFC66D);
  Color bgColor = Color(0x7fFFC66D);
  String payType = "01";

  ///充值价格
  Widget _priceWidget() {
    return Container(
      margin: EdgeInsets.all(10),
      child: Row(
        children: _price
            .map((item) => Builder(builder: (context) {
                  return Expanded(
                    flex: 1,
                    child: GestureDetector(
                      child: Container(
                        height: 100,
                        margin: EdgeInsets.only(left: 10, right: 10),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(
                            color: current == item['id']
                                ? borderColor
                                : Color(0xffDDDDDD),
                            width: 1,
                          ),
                          color: current == item['id'] ? bgColor : Colors.white,
                        ),
                        alignment: Alignment.center,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              item['title'],
                              style: TextStyle(color: Color(0xff666666)),
                            ),
                            SizedBox(height: 10),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                Text(
                                  "￥",
                                  style: TextStyle(
                                    color: borderColor,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                                Text(
                                  item['price'],
                                  style: TextStyle(
                                    color: borderColor,
                                    fontSize: 26,
                                    fontWeight: FontWeight.w800,
                                  ),
                                )
                              ],
                            ),
                            SizedBox(height: 10),
                            Text(
                              "原价${item['oldPrice']}",
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 12),
                            ),
                          ],
                        ),
                      ),
                      onTap: () {
                        setState(() {
                          current = item['id'];
                        });
                      },
                    ),
                  );
                }))
            .toList(),
      ),
    );
  }

  ///充值方式
  Widget _payWidget() {
    return Container(
      margin: EdgeInsets.all(20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          GestureDetector(
            child: Row(
              children: <Widget>[
                Icon(
                  FontAwesomeIcons.alipay,
                  size: 28,
                  color: Color(0XFF00A1E9),
                ),
                SizedBox(width: 10),
                Text(
                  "支付宝支付",
                  style: TextStyle(fontWeight: FontWeight.w600),
                ),
                Expanded(flex: 1, child: Container()),
                Icon(
                  payType == '01'
                      ? Icons.check_box
                      : Icons.check_box_outline_blank,
                  color: borderColor,
                ),
              ],
            ),
            onTap: () {
              setState(() {
                payType = "01";
              });
            },
          ),
          SizedBox(height: 20),
          GestureDetector(
            child: Row(
              children: <Widget>[
                Icon(
                  FontAwesomeIcons.weixin,
                  size: 28,
                  color: Color(0XFF01D00E),
                ),
                SizedBox(width: 10),
                Text(
                  "微信支付",
                  style: TextStyle(fontWeight: FontWeight.w600),
                ),
                Expanded(flex: 1, child: Container()),
                Icon(
                  payType == '02'
                      ? Icons.check_box
                      : Icons.check_box_outline_blank,
                  color: borderColor,
                ),
              ],
            ),
            onTap: () {
              setState(() {
                payType = "02";
              });
            },
          ),
        ],
      ),
    );
  }

  ///底部按钮
  Widget _bottomWidget() {
    String disc = _price[current]['disc'];
    return Container(
      height: 48,
      width: double.infinity,
      color: Colors.white,
      alignment: Alignment.center,
      padding: EdgeInsets.only(left: 10),
      child: Row(
        children: <Widget>[
          Text('总计:'),
          Text(
            '￥',
            style: TextStyle(
              color: borderColor,
              fontSize: 12,
              fontWeight: FontWeight.w600,
            ),
          ),
          Text(
            _price[current]['price'],
            style: TextStyle(
              color: borderColor,
              fontSize: 26,
              fontWeight: FontWeight.w600,
            ),
          ),
          SizedBox(width: 6),
          Offstage(
            offstage: disc == '0',
            child: Text(
              "已优惠￥$disc",
              style: TextStyle(
                fontSize: 12,
                color: Color(0xffDDDDDD),
              ),
            ),
          ),
          Expanded(flex: 1, child: Container()),
          GestureDetector(
            onTap: () {
              _getPayFor();
            },
            child: Container(
              color: borderColor,
              height: 48,
              width: 96,
              alignment: Alignment.center,
              child: Text(
                "确认支付",
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _getPayFor() async {
    if (loading) {
      Toast.show("订单创建中,请勿重复操作");
      return;
    }
    setState(() {
      loading = true;
    });
    Map<String, String> params = Map();
    params['month'] = "${_price[current]['num']}";
    params['desc'] = "${_price[current]['title']}Vip会员";
    params['payType'] = "$payType";
    params['price'] = _price[current]['price'];
    Http.post(Api.URL_ORDER_CHARGE, params: params,
        successCallBack: (data) async {
      setState(() {
        loading = false;
      });
      Order payInfo = Order.fromJson(json.decode(data));
      if (payType == '01') {
        var result = await tobias.aliPay(payInfo.orderInfo,
            evn: tobias.AliPayEvn.ONLINE);
        Map<String, dynamic> payResult = jsonDecode(json.encode(result));

        print("订单结果：$payResult");
        if (int.parse(payResult['resultStatus']) == 9000) {
          print('支付成功');
          var payInfo =
              json.decode(payResult['result'])['alipay_trade_app_pay_response'];
          print('payinfo=$payInfo');
          Navigator.of(context).push(RouteSlide(
            PaySuccess(
              payInfo['timestamp'],
              payInfo['out_trade_no'],
              payInfo['trade_no'],
              payInfo['total_amount'],
            ),
          ));
        }
      } else if (payType == '02') {
        var wxPay = json.decode(payInfo.orderInfo);
        orderId = payInfo.orderId;
        fluwx.payWithWeChat(
          appId: wxPay['appid'],
          partnerId: wxPay['partnerid'],
          prepayId: wxPay['prepayid'],
          packageValue: wxPay['package'],
          nonceStr: wxPay['noncestr'],
          timeStamp: int.parse(wxPay['timestamp']),
          sign: wxPay['sign'],
        );
      }
    }, errorCallBack: (error) {
      setState(() {
        loading = false;
      });
      Toast.show(error);
    });
  }
}
